﻿using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;
using XUCore.Extensions;
using XUCore.WeChat.Enterprise.Apis.Member;
using XUCore.WeChat.Enterprise.Apis.Sns;

namespace XUCore.WeChat.Enterprise.Net
{
    /// <summary>
    /// 请自行添加 [AllowAnonymous] [EnterpriseWeChatOAuthFilter]
    /// </summary>
    //[AllowAnonymous]
    //[EnterpriseWeChatOAuthFilter]
    public class EnterpriseWeChatPageModelBase : PageModel
    {
        /// <summary>
        ///     是否是企业成员（如果是企业成员 则是true，否则false是外部用户）
        /// </summary>
        public bool IsEmployee => UserId.IsEmpty();

        /// <summary>
        /// 获取企业成员的UserId
        /// </summary>
        public string UserId
        {
            get
            {
                var userId = Request.HttpContext.Items[EnterpriseWeChatConsts.COOKIE_ENTERPRISE_USERID]?.ToString();
                if (string.IsNullOrEmpty(userId))
                {
                    userId = Request.Cookies[EnterpriseWeChatConsts.COOKIE_ENTERPRISE_USERID];
                }
                return userId;
            }
        }

        /// <summary>
        /// 获取WebTicket
        /// </summary>
        public string WebTicket
        {
            get
            {
                var webAccessToken = Request.HttpContext.Items[EnterpriseWeChatConsts.COOKIE_ENTERPRISE_WEBTICKET]?.ToString();
                if (string.IsNullOrEmpty(webAccessToken))
                {
                    webAccessToken = Request.Cookies[EnterpriseWeChatConsts.COOKIE_ENTERPRISE_WEBTICKET];
                }

                return webAccessToken;
            }
        }

        /// <summary>
        /// 获取非企业成员的OpenId
        /// </summary>
        public string OpenId
        {
            get
            {
                var openId = Request.HttpContext.Items[EnterpriseWeChatConsts.COOKIE_ENTERPRISE_OPENID]?.ToString();
                if (string.IsNullOrEmpty(openId))
                {
                    openId = Request.Cookies[EnterpriseWeChatConsts.COOKIE_ENTERPRISE_OPENID];
                }
                return openId;
            }
        }

        /// <summary>
        /// 获取外部联系人的ExternalUserId
        /// </summary>
        public string ExternalUserId
        {
            get
            {
                var externalUserId = Request.HttpContext.Items[EnterpriseWeChatConsts.COOKIE_ENTERPRISE_EXTERNALUSERID]?.ToString();
                if (string.IsNullOrEmpty(externalUserId))
                {
                    externalUserId = Request.Cookies[EnterpriseWeChatConsts.COOKIE_ENTERPRISE_EXTERNALUSERID];
                }
                return externalUserId;
            }
        }

        /// <summary>
        /// 代开发模板Id SuiteId
        /// </summary>
        public string SuiteId
        {
            get
            {
                return Request.HttpContext.Request.Query["suiteid"].SafeString();
            }
        }

        /// <summary>
        /// 企业id CorpId
        /// </summary>
        public string CorpId
        {
            get
            {
                //appid 则是 corpid

                string corpid = Request.HttpContext.Request.Query["appid"].ToString();
                if (corpid.IsEmpty())
                    corpid = Request.HttpContext.Request.Query["corpid"].ToString();

                return corpid;
            }
        }

        /// <summary>
        /// 企业应用id AgentId
        /// </summary>
        public int AgentId
        {
            get
            {
                return Request.HttpContext.Request.Query["agentid"].SafeString().ToInt();
            }
        }

        /// <summary>
        /// 获取企业员工信息
        /// </summary>
        /// <returns></returns>
        protected async Task<EnterpriseUserDetailApiResult> GetEmployeeUserInfoAsync()
        {
            if (WebTicket.IsEmpty()) return default;

            if (CorpId.IsEmpty())
                throw new WeChatSdkException("corpid 或 appid 不可为空");

            if (AgentId <= 0)
                throw new WeChatSdkException("agentid 不可为空");

            var tokenManager = Request.HttpContext.RequestServices.GetRequiredService<IEnterpriseWeChatTokenManager>();
            var token = await tokenManager.GetAccessTokenAsync(SuiteId, CorpId, AgentId);

            var snsApi = Request.HttpContext.RequestServices.GetRequiredService<IEnterpriseSnsApi>();

            var result = default(EnterpriseUserDetailApiResult);

            if (IsEmployee)
            {
                result = await snsApi.GetUserDetailAsync(token, new UserDetailInput { user_ticket = WebTicket });

                result.EnsureSuccess();
            }

            return result;
        }

        /// <summary>
        /// 获取外部联系人详情（客户详情，且有企业员工跟进的客户）
        /// </summary>
        /// <param name="cursor">上次请求返回的next_cursor，首次请求可不填</param>
        /// <returns></returns>
        protected async Task<MemberApiResult> GetExternalContactInfoAsync(string cursor = "")
        {
            if (ExternalUserId.IsEmpty()) return default;

            if (CorpId.IsEmpty())
                throw new WeChatSdkException("corpid 或 appid 不可为空");

            if (AgentId <= 0)
                throw new WeChatSdkException("agentid 不可为空");

            var tokenManager = Request.HttpContext.RequestServices.GetRequiredService<IEnterpriseWeChatTokenManager>();
            var token = await tokenManager.GetAccessTokenAsync(SuiteId, CorpId, AgentId);

            var memberApi = Request.HttpContext.RequestServices.GetRequiredService<IEnterpriseMemberApi>();

            var result = default(MemberApiResult);

            if (IsEmployee)
            {
                result = await memberApi.GetMemberDetailAsync(token, ExternalUserId);

                result.EnsureSuccess();
            }

            return result;
        }
    }
}
